package com.fix.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fix.entity.Authority;

/**
 *  权限过滤器
 */
@WebFilter("/vip/*")
public class AuthorityFilter implements Filter {
 
	public void destroy() {
		 
	}

	 
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		// 检查你是否有权限 
		HttpSession session =req.getSession();
		List<Authority> userAuths =(List)session.getAttribute("userAuths");  //用户权限列表
		//你正在访问的 
		String uri =req.getRequestURI();
		System.out.println("权限过滤...."+uri);
		
		boolean ok = false;
		for (Authority auth : userAuths) {  //  查找你是否拥有这个权利
			if(uri.endsWith( auth.getAuthPath())) {
				ok =true;
				break;
			}
		}		
		if(ok) {
			chain.doFilter(request, response); //放行
		}else {
			res.sendRedirect("/auth/noauth.html"); //无权访问
		} 
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
